# coding: utf-8

from functools import reduce

import django_filters

from . import models as app_models


class OpLogFilter(django_filters.rest_framework.FilterSet):

    id_type = django_filters.BaseInFilter(
        method='id_type_filter',
    )

    def id_type_filter(self, queryset, name, value):
        filter_kwargs = [
            {
                'object_id': id_type[0].strip(),
                'object_type': id_type[1].strip(),
            }
            for id_type in [
                [i.strip() for i in item.split(':') if i.strip()]
                for item in value
            ] if len(id_type) == 2 and id_type[0].isdigit()
        ]
        return reduce(
            lambda x, y: x | y,
            [queryset.filter(**kwargs) for kwargs in filter_kwargs]
        )

    class Meta:
        model = app_models.OpLog
        fields = {
            'object_id': ['exact'],
            'object_type': ['exact', 'in'],
            'operator_time': ['range'],
        }
